<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\api\items\common;

use api\upload\exception\UploadException;
use app\common\repositories\system\upload\SystemUploadFileRepository;
use app\controller\api\Base;
use think\App;

class UploadFile extends Base
{
    protected $repository;

    public function __construct(App $app, SystemUploadFileRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }

    public function uploadImageAdd()
    {
        $field = ($this->request->param('field') ? $this->request->param('field') : 'file');
        $dir = ($this->request->param('dir') ? $this->request->param('dir') : 'user');
        try {
            $upload = \app\common\services\UploadService::init($this->request->itemsId, $dir);
            $res = $upload->uploadImageFile($field);
            $fileInfo = $res['data']['fileInfo'];
            $groupId = $this->request->param('group_id', 0, 'intval');
            $data = [
                'source' => 'users',
                'group_id' => $groupId,
                'show_src' => $fileInfo['show_src'],
                'upload_path' => $fileInfo['upload_path'],
                'storage_type' => $fileInfo['storage_type'],
                'file_md5' => $fileInfo['file_md5'],
                'file_size' => $fileInfo['file_size'],
                'file_type' => $fileInfo['file_type'],
                'file_name' => $fileInfo['file_name'],
                'user_id' => $this->request->userId ?? 0,
                'items_id' => $this->request->itemsId
            ];
            $this->repository->create($data);
            return app('api_return')->success([
                'src' => $res['data']['src']
            ]);
        } catch (UploadException $e) {
            return app('api_return')->error($e->getMessage());
        }
    }
}